package servlet.song;

import pojo.Songs;
import service.SongsService;
import service.impl.SongsServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

@WebServlet("/song/listByUploader")
public class ListByUploader extends HttpServlet {

    // 创建歌曲服务对象
    private final SongsService songsService = new SongsServiceImpl();
    private static final Logger logger = Logger.getLogger(ListByUploader.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 获取上传者ID参数
            String uploaderIdParam = req.getParameter("uploaderId");

            // 验证上传者ID是否有效
            if (uploaderIdParam == null || uploaderIdParam.isEmpty()) {
                sendErrorResponse(resp, "上传者ID不能为空", "/song/list.jsp");
                return;
            }

            int uploaderId;
            try {
                uploaderId = Integer.parseInt(uploaderIdParam);
            } catch (NumberFormatException e) {
                sendErrorResponse(resp, "无效的上传者ID", "/song/list.jsp");
                return;
            }

            // 调用服务层获取该上传者上传的所有歌曲
            List<Songs> songsList = songsService.getSongsByUploaderId(uploaderId);

            // 设置响应的内容类型为HTML
            resp.setContentType("text/html;charset=UTF-8");

            if (songsList != null && !songsList.isEmpty()) {
                // 如果找到了歌曲，返回歌曲列表的HTML页面
                req.setAttribute("songsList", songsList);
                req.getRequestDispatcher("/song/listByUploader.jsp").forward(req, resp);
            } else {
                // 如果没有找到歌曲，返回提示信息
                sendErrorResponse(resp, "没有找到该上传者的歌曲", "/song/list.jsp");
            }

        } catch (Exception e) {
            logger.severe("Error occurred in ListByUploader servlet: " + e.getMessage());
            sendErrorResponse(resp, "服务器内部错误，请稍后再试", "/song/list.jsp");
        }
    }

    // 辅助方法：统一处理错误信息的返回
    private void sendErrorResponse(HttpServletResponse resp, String message, String redirectUrl) throws IOException {
        resp.getWriter().write("<script>alert('" + message + "');window.location.href='" + redirectUrl + "';</script>");
    }
}
